#include "G_LedEffect.h"
#include "G_Led.h"
#include "G_Beep.h"

static void openLED(uint8_t ledNum);
static void closeLED(uint8_t ledNum);
// 初始化LED状态
void led_init(led_t *led, uint8_t ledNum) {
    led->ledNum = ledNum;
    led->counter = 0;
    led->current_phase = 0;
    led->total_phases = 0;
    led->loop = false;
}

// 设置LED特效
void led_set_effect(led_t *led, led_effect_phase_t *phases, uint8_t total_phases, bool loop) {
    for (uint8_t i = 0; i < total_phases; i++) {
        led->phases[i] = phases[i];
    }
    led->total_phases = total_phases;
    led->loop = loop;
    led->counter = 0;
    led->current_phase = 0;
}

// LED特效控制函数
void led_effect_handler(led_t *led) {
    if (led->total_phases == 0) return;

    led_effect_phase_t *phase = &led->phases[led->current_phase];
    if (led->counter < phase->on_time) {
        // 打开LED
        openLED(led->ledNum);
    } else if (led->counter < phase->on_time + phase->off_time) {
        // 关闭LED
       closeLED(led->ledNum);
    } else {
        led->counter = 0;
        led->current_phase++;
        if (led->current_phase >= led->total_phases) {
            if (led->loop) {
                led->current_phase = 0; // 循环
            } else {
                // 结束特效
                led->total_phases = 0;
                // gpio_write(led->pin, LOW); // 确保LED关闭
                return;
            }
        }
    }
    led->counter++;
}

static void openLED(uint8_t ledNum){
	if(ledNum==4){
		beepOn();
	}else
	{
		ledOn(ledNum);
	}
}
static void closeLED(uint8_t ledNum){
	if(ledNum==4){
		beepOff();
	}else
	{
		ledOff(ledNum);
	}
}

